package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.UserRoleListVo;
import com.xiaoxu.intranetweb.util.SzResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
/**
 * web端用户权限业务层
 * @author xiaoxu
 * @date 2023/3/22 13:00
 * @version 1.0
 * @since 1.0
 */
public class RoleInfoFunctionWebBu {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleInfoFunctionWebService sysRoleInfoFunctionWebService;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysPartService sysPartService;
    @Autowired
    private ISysUserRoleConnService sysUserRoleConnService;

    /**
     * 用户权限查询业务
     *
     * @param userId 用户id
     * @return SzResult
     */

//    web
    public List<SysRoleInfoFunctionWeb> getUserFunction(String userId) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", userId);
        queryWrapper.eq("DEL_FLAG", "0");
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        String getAppAuthority2 = sysUser.getAppAuthority2();
        if (getAppAuthority2 == null || getAppAuthority2.equals("")) {
            return null;
        }
        Integer[] integers = new Integer[getAppAuthority2.length()];
        List<Integer> functionNum = new LinkedList<>();
        for (int i = 0; i < getAppAuthority2.length(); i++) {
            integers[i] = Integer.valueOf(getAppAuthority2.substring(i, i + 1));
        }
        for (int i = 0; i < integers.length; i++) {
            if (integers[i] == 1) {
                functionNum.add(i);
            }
        }
//                将functionNum代入到sys_role_info_function表中查询对应的功能值
        if (functionNum.size() != 0){
            QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("WEB_FUNCTION_NUMBER", functionNum);
        queryWrapper.ne("WEB_FUNCTION_DEL_FLAG", 1);
        List<SysRoleInfoFunctionWeb> sysRoleInfoFunctionWebs = sysRoleInfoFunctionWebService.list(queryWrapper1);

        return sysRoleInfoFunctionWebs;
    }else {
            return null;
        }
    }


    public SzResult getAuthority(String userId) {
        QueryWrapper<SysUserRoleConn> sysUserRoleConnQw = new QueryWrapper<>();
        sysUserRoleConnQw.eq("USER_ID",userId);
        SysUserRoleConn user = sysUserRoleConnService.getOne(sysUserRoleConnQw);
        String code = sysRoleService.getById(user.getRoleId()).getRoleCode().substring(3);
        QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("WEB_FUNCTION_BELONG_ROLE_LEVEL",code);
        queryWrapper.ne("WEB_FUNCTION_DEL_FLAG",1);
        List<UserRoleListVo> sysRoleInfoWebFunctions = sysRoleInfoFunctionWebService.list(queryWrapper).stream().map(item->{
            UserRoleListVo userRoleListVo = new UserRoleListVo();
            BeanUtils.copyProperties(item,userRoleListVo);
            return userRoleListVo;
        }).collect(Collectors.toList());
        List<SysRoleInfoFunctionWeb> sysRoleInfos = getUserFunction(userId);
        List<String> userFunctionIds;

// 检查是否为空，如果为空，则直接设置所有item的isEnable为1
        if (sysRoleInfos == null || sysRoleInfos.size()==0) {
            for (UserRoleListVo item : sysRoleInfoWebFunctions) {
                item.setIsEnable(1);
            }
        } else {
            // 非空情况，获取所有ID
            userFunctionIds = sysRoleInfos.stream()
                    .map(SysRoleInfoFunctionWeb::getId)
                    .collect(Collectors.toList());

            // 根据userFunctionIds设置isEnable
            for (UserRoleListVo item : sysRoleInfoWebFunctions) {
                if (userFunctionIds.contains(item.getId())) {
                    item.setIsEnable(0);
                } else {
                    item.setIsEnable(1);
                }
            }
        }
        return SzResult.success(sysRoleInfoWebFunctions);
    }

    public SzResult getWebAuthority(String id) {
        QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.ne("WEB_FUNCTION_DEL_FLAG", "1"));
        List<UserRoleListVo> allListRoleInfo = sysRoleInfoFunctionWebService.list(queryWrapper).stream()
                .map(item -> {
                    UserRoleListVo userRoleListVo = new UserRoleListVo();
                    BeanUtils.copyProperties(item, userRoleListVo);
                    // 初始化为0，后续根据条件更新
                    userRoleListVo.setIsEnable(1);
                    return userRoleListVo;
                })
                .collect(Collectors.toList());

        SysPart sysPart = sysPartService.getById(id);
        Integer[] integers = new Integer[sysPart.getDefaultCodeWeb().length()];
        List<Integer> functionNum = new ArrayList<>();
        for (int i = 0; i < sysPart.getDefaultCodeWeb().length(); i++) {
            integers[i] = Integer.valueOf(sysPart.getDefaultCodeWeb().substring(i, i + 1));
        }
        for (int i = 0; i < integers.length; i++) {
            if (integers[i] == 1) {
                functionNum.add(i);
            }
        }

        if (functionNum.isEmpty()) {
            // 如果functionNum为空，设置所有UserRoleListVo的isEnable为0
            for (UserRoleListVo userRoleListVo : allListRoleInfo) {
                userRoleListVo.setIsEnable(1);
            }
        } else {
            QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("WEB_FUNCTION_NUMBER", functionNum);
            List<SysRoleInfoFunctionWeb> sysRoleInfoFunctions = sysRoleInfoFunctionWebService.list(queryWrapper1);

            Set<String> enabledFunctionIds = sysRoleInfoFunctions.stream()
                    .map(SysRoleInfoFunctionWeb::getId)
                    .collect(Collectors.toSet());

            for (UserRoleListVo userRoleListVo : allListRoleInfo) {
                // 根据ID是否存在于enabledFunctionIds中来决定isEnable的值
                userRoleListVo.setIsEnable(enabledFunctionIds.contains(userRoleListVo.getId()) ? 0 : 1);
            }
        }
        return SzResult.success(allListRoleInfo);
    }


    /**
     * 用户权限修改业务
     *
     * @param userId 用户id
     *               functionNum 功能值
     *               state 状态(1为开启,0为关闭)
     * @return SzResult
     */
    public SzResult updateUserFunction(String token, String userId, String functionNum, String state,String plantId) throws Exception {
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ID", userId);
        updateWrapper.eq("DEL_FLAG", "0");
        SysUser sysUser = sysUserService.getOne(updateWrapper);
        String appAuthority1 = sysUser.getAppAuthority1();
        Integer[] integers = new Integer[appAuthority1.length()];
        for (int i = 0; i < appAuthority1.length(); i++) {
            integers[i] = Integer.valueOf(appAuthority1.substring(i, i + 1));
        }
        if (state.equals("1")) {
            integers[Integer.parseInt(functionNum)] = 1;
            QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("WEB_FUNCTION_NUMBER", functionNum);
            SysRoleInfoFunctionWeb sysRoleInfoFunction = sysRoleInfoFunctionWebService.getOne(queryWrapper1);
            SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
            sysLogBu.logRecord("修改用户权限", user1.getTrueName(), "开启了用户" + sysUser.getUserName() + "的【" + sysRoleInfoFunction.getWebFunctionBelongExplain() + "】权限",plantId);
        } else {
            integers[Integer.parseInt(functionNum)] = 0;
            QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("WEB_FUNCTION_NUMBER", functionNum);
            SysRoleInfoFunctionWeb sysRoleInfoFunction = sysRoleInfoFunctionWebService.getOne(queryWrapper1);
            SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
            sysLogBu.logRecord("修改用户权限", user1.getTrueName(), "关闭了用户" + sysUser.getUserName() + "的【" + sysRoleInfoFunction.getWebFunctionBelongExplain() + "】权限",plantId);
        }
        String s = Arrays.toString(integers).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
        sysUser.setAppAuthority1(s);
        sysUserService.updateById(sysUser);
        return SzResult.Success();
    }

    /**
     * 查询roleInfoFunction表中的所有数据业务层
     *
     * @param
     * @return SzResult
     */
    public SzResult getRoleFunction(String page,String pageSize,String functionName) {
        //page和pageSize为空时，查询所有数据
        if (page == null || page.equals("") || pageSize == null || pageSize.equals("")) {
            QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper = new QueryWrapper<>();
            queryWrapper.and(wrapper -> wrapper.ne("WEB_FUNCTION_DEL_FLAG", "1").or().isNull("WEB_FUNCTION_DEL_FLAG"));
            List<SysRoleInfoFunctionWeb> list = sysRoleInfoFunctionWebService.list(queryWrapper);
            int total = list.size();
            Map<String, Object> map = new HashMap<>();
            map.put("total", total);
            map.put("list", list);
            return SzResult.success(map);
        }
        Page<SysRoleInfoFunctionWeb> sysRoleInfoFunctionIPage = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
        QueryWrapper<SysRoleInfoFunctionWeb> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(functionName != null && !functionName.equals(""),"WEB_FUNCTION_EXPLAIN", functionName).or().like(functionName != null && !functionName.equals(""),"WEB_FUNCTION_NAME", functionName);
        queryWrapper.and(wrapper -> wrapper.ne("WEB_FUNCTION_DEL_FLAG", "1").or().isNull("WEB_FUNCTION_DEL_FLAG"));
        Page<SysRoleInfoFunctionWeb> sysRoleInfoFunctionPage = sysRoleInfoFunctionWebService.page(sysRoleInfoFunctionIPage, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", sysRoleInfoFunctionPage.getTotal());
        map.put("list", sysRoleInfoFunctionPage.getRecords());
        return SzResult.success(map);
    }

    /**
     * 修改roleInfoFunction表中的WEB_FUNCTION_BELONG_ROLE_LEVEL数据所有数据业务层
     *
     * @param functionNum 功能值
     *                    functionBelongRoleLevel 角色等级0为管理员,1为单位,2为司机
     *                    token 令牌
     * @return SzResult
     */
    public SzResult updateRoleFunctionLevel(String token, String functionNum, String functionBelongRoleLevel, String state,String plantId) throws Exception {
//       WEB_FUNCTION_BELONG_ROLE_LEVEL 0为管理员,1为单位,2为司机
        UpdateWrapper<SysRoleInfoFunctionWeb> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("WEB_FUNCTION_NUMBER", functionNum);
        SysRoleInfoFunctionWeb sysRoleInfoFunctionWeb = sysRoleInfoFunctionWebService.getOne(updateWrapper);
        if (state.equals("0")) {
//        sysRoleInfoFunction.setWebFunctionBelongRoleLevel存的字符串012
            String webFunctionBelongRoleLevel = sysRoleInfoFunctionWeb.getWebFunctionBelongRoleLevel();
            String[] split = new String[webFunctionBelongRoleLevel.length()];
            for (int i = 0; i < webFunctionBelongRoleLevel.length(); i++) {
                split[i] = webFunctionBelongRoleLevel.substring(i, i + 1);
            }
//  检查传入的值是否在split中
            boolean contains = Arrays.asList(split).contains(functionBelongRoleLevel);
            if (contains) {
                return SzResult.Error("该权限已经存在");
            } else {
//            不存在的话就把functionBelongRoleLevel放到split中，然后转成字符串存回数据库
                String[] split1 = new String[split.length + 1];
                for (int i = 0; i < split.length; i++) {
                    split1[i] = split[i];
                }
                split1[split.length] = functionBelongRoleLevel;
                String s = Arrays.toString(split1).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
                sysRoleInfoFunctionWeb.setWebFunctionBelongRoleLevel(s);
                sysRoleInfoFunctionWebService.updateById(sysRoleInfoFunctionWeb);
                SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
                if (functionBelongRoleLevel.equals("0"))
                    sysLogBu.logRecord("修改权限", user1.getTrueName(), "新增了权限【" + sysRoleInfoFunctionWeb.getWebFunctionBelongExplain() + "】的权限等级为【管理员】级别",plantId);
                if (functionBelongRoleLevel.equals("1"))
                    sysLogBu.logRecord("修改权限", user1.getTrueName(), "新增了权限【" + sysRoleInfoFunctionWeb.getWebFunctionBelongExplain() + "】的权限等级为【单位】级别",plantId);
                if (functionBelongRoleLevel.equals("2"))
                    sysLogBu.logRecord("修改权限", user1.getTrueName(), "新增了权限【" + sysRoleInfoFunctionWeb.getWebFunctionBelongExplain() + "】的权限等级为【司机】级别",plantId);
            }
        } else {
            String webFunctionBelongRoleLevel = sysRoleInfoFunctionWeb.getWebFunctionBelongRoleLevel();
            String[] split = new String[webFunctionBelongRoleLevel.length()];
            for (int i = 0; i < webFunctionBelongRoleLevel.length(); i++) {
                split[i] = webFunctionBelongRoleLevel.substring(i, i + 1);
            }
            //  检查传入的值是否在split中
            boolean contains = Arrays.asList(split).contains(functionBelongRoleLevel);
            if (!contains) {
                return SzResult.Error("该权限不存在");
            }
            List<String> strings = Arrays.asList(split);
            List<String> list = new ArrayList<>(strings);
            list.remove(functionBelongRoleLevel);
            String s = Arrays.toString(list.toArray()).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
            sysRoleInfoFunctionWeb.setWebFunctionBelongRoleLevel(s);
            sysRoleInfoFunctionWebService.updateById(sysRoleInfoFunctionWeb);
            SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
            if (functionBelongRoleLevel.equals("0"))
                sysLogBu.logRecord("修改权限", user1.getTrueName(), "删除了权限【" + sysRoleInfoFunctionWeb.getWebFunctionBelongExplain() + "】的权限等级中的【管理员】级别",plantId);
            if (functionBelongRoleLevel.equals("1"))
                sysLogBu.logRecord("修改权限", user1.getTrueName(), "删除了权限【" + sysRoleInfoFunctionWeb.getWebFunctionBelongExplain() + "】的权限等级中的【单位】级别",plantId);
            if (functionBelongRoleLevel.equals("2"))
                sysLogBu.logRecord("修改权限", user1.getTrueName(), "删除了权限【" + sysRoleInfoFunctionWeb.getWebFunctionBelongExplain() + "】的权限等级中的【司机】级别",plantId);
        }
        return SzResult.Success();
    }
}
